package com.jun.rabbitmq.consumer.config;

import lombok.Data;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.RetryInterceptorBuilder;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.retry.RejectAndDontRequeueRecoverer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.interceptor.StatefulRetryOperationsInterceptor;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

import java.time.Duration;

/**
 * @author yuejun.li
 * @date 2024/4/24 17:21:10
 * 消费者配置
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.rabbitmq.listener.simple.retry")
@ConditionalOnProperty(name = "spring.rabbitmq.listener.simple.retry.enabled", havingValue = "true")
public class ConsumerConfig {

    //最大重试次数
    private int maxAttempts;

    //重试间隔时间（单位毫秒）
    private Duration initialInterval;

    //重试因子 重试间隔时间*重试因子=下一次的间隔时间，不能超过max-interval
    private double multiplier;

    //重试最大时间间隔（单位毫秒）
    private Duration maxInterval;

    //应答模式
    private AcknowledgeMode acknowledgeMode;

    /*@Bean
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);

        StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful()
                .maxAttempts(this.maxAttempts)
                // 设置重试间隔时间
                .backOffOptions(this.initialInterval.toMillis(), this.multiplier, this.maxInterval.toMillis())
                // 重试恢复策略
                .recoverer(new RejectAndDontRequeueRecoverer())
                .build();
        //设置失败重试拦截
        factory.setAdviceChain(interceptor);
        //消息转换
        //factory.setMessageConverter(new Jackson2JsonMessageConverter());
        //应答方式
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }*/

}
